package com.mftour.moudles.controller;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;

import com.mftour.common.Constant;
import com.mftour.moudles.vo.AjaxResponse;

/**
 * 必须要@EnableWebMvc注解才生效， 或者是配置mvc namespace declaration，未测试
 * 
 * @author Administrator
 *
 */
@RestControllerAdvice
@EnableWebMvc
// @ControllerAdvice
public class ErrorAdvice {

	private static final Logger logger = LoggerFactory.getLogger(ErrorAdvice.class);

	@ExceptionHandler({ BindException.class, HttpMessageNotReadableException.class })
	public AjaxResponse exp400(HttpServletRequest request, Exception e) {
		AjaxResponse ajaxResponse = new AjaxResponse(Constant.RS_CODE_ERROR, "参数绑定错误！", e.getMessage());		
		logger.error("", e);
		return ajaxResponse;
	}

	@ExceptionHandler(DataIntegrityViolationException.class)
	public AjaxResponse expSql(HttpServletRequest request, Exception e) {
		AjaxResponse ajaxResponse = (AjaxResponse) request.getAttribute("ajaxResponse");
		if (ajaxResponse == null) {
			ajaxResponse = new AjaxResponse(Constant.RS_CODE_ERROR, Constant.RS_MSG_ERROR, e.getMessage());
		}
		logger.error("", e);
		return ajaxResponse;
	}
}
